import { createRouter, createWebHashHistory,createWebHistory, RouteRecordRaw } from 'vue-router'
import { staticRoutes } from './constantRoutes'
import { useUserInfoStore } from '@/store/modules/model/userInfoModel'


const router = createRouter({
  history: createWebHistory(),
  routes: staticRoutes as RouteRecordRaw[],
  // 刷新时，滚动条位置还原
  scrollBehavior: () => ({ left: 0, top: 0 }),
})

router.beforeEach(async (to, from, next)=>{
  let userInfoStore = useUserInfoStore()
  let token = userInfoStore.token;
  let userInfo = userInfoStore.userInfo;
  if(token){
    //表示有令牌，即已登录
    if(to.path === '/login'){
      next('/')
    }else{
      if(userInfo.name){
        //表示已经获取了用户信息，放行
        next()
      }else{
        //表示未获取用户信息，先获取用户信息，再放行
        await userInfoStore.getUserInfo();
        next()
      }
    }
  }else{
    //表示没有令牌，即未登录
    if(to.path === '/login'){
      next()
    }else{
      next('/login')
    }
  }
})

export default router
